package org.qhhc.bionioaio.bio.Client;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;

public class SwingChatClient extends JFrame {
    private String DEFAULT_SERVER_HOST = "192.168.111.70";
    private int DEFAULT_PORT = 8888;
    private final String QUIT = "quit";
    
    private Socket socket;
    private BufferedReader reader;
    private BufferedWriter writer;
    private String username;
    
    // UI Components
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JButton quitButton;
    private JPanel inputPanel;
    private JLabel statusLabel;
    
    public SwingChatClient() {
        // 获取用户名
        username = JOptionPane.showInputDialog(this, "请输入您的用户名:", "登录", JOptionPane.PLAIN_MESSAGE);
        if (username == null || username.trim().isEmpty()) {
            username = "用户" + System.currentTimeMillis() % 1000;
        }
        
        // Set up the UI
        initializeUI();
        
        // Connect to server
        connectToServer();
    }
    
    private void initializeUI() {
        // Set window properties
        setTitle("聊天客户端 - " + username);
        setSize(500, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Create chat area
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        
        // Create status panel
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusLabel = new JLabel("状态: 未连接");
        statusPanel.add(statusLabel);
        
        // Create input components
        inputField = new JTextField(20);
        sendButton = new JButton("发送");
        quitButton = new JButton("退出");
        
        // Add action listeners
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
        
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
        
        quitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    sendMsg(QUIT);
                    close();
                    System.exit(0);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
        
        // Add window closing listener
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    sendMsg(QUIT);
                    close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
        
        // Layout components
        inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        inputPanel.add(inputField, BorderLayout.CENTER);
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(sendButton);
        buttonPanel.add(quitButton);
        
        inputPanel.add(buttonPanel, BorderLayout.EAST);
        
        // Add components to frame
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(statusPanel, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(inputPanel, BorderLayout.SOUTH);
    }
    
    private void connectToServer() {
        try {
            // Create socket
            socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_PORT);
            
            // Create IO streams
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            // Send username to server
            sendMsg("USERNAME:" + username);
            
            // Start message receiving thread
            new Thread(new MessageReceiver()).start();
            
            // Show connection success
            updateStatus("已连接");
            appendToChatArea("系统", "成功连接到服务器");
        } catch (IOException e) {
            updateStatus("连接失败");
            appendToChatArea("系统", "连接服务器失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void sendMessage() {
        String message = inputField.getText().trim();
        if (!message.isEmpty()) {
            try {
                sendMsg(message);
                appendToChatArea("我", message);
                inputField.setText("");
            } catch (IOException e) {
                appendToChatArea("系统", "发送消息失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    
    // 发送消息给服务器
    public void sendMsg(String msg) throws IOException {
        if (!socket.isOutputShutdown()) {
            writer.write(msg + "\n");
            writer.flush();
        }
    }
    
    // 关闭连接
    public void close() {
        try {
            if (writer != null) writer.close();
            if (reader != null) reader.close();
            if (socket != null) socket.close();
            updateStatus("已断开");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 更新状态
    private void updateStatus(final String status) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                statusLabel.setText("状态: " + status);
            }
        });
    }
    
    // 添加消息到聊天区域
    private void appendToChatArea(final String sender, final String message) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                String timestamp = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date());
                chatArea.append(String.format("[%s] %s: %s\n", timestamp, sender, message));
                // 自动滚动到底部
                chatArea.setCaretPosition(chatArea.getDocument().getLength());
            }
        });
    }
    
    // 接收消息的线程
    private class MessageReceiver implements Runnable {
        @Override
        public void run() {
            try {
                String message;
                while ((message = reader.readLine()) != null) {
                    if (message.startsWith("USERNAME:")) {
                        // 处理用户名消息
                        String[] parts = message.split(":", 2);
                        if (parts.length == 2) {
                            appendToChatArea("系统", parts[1] + " 加入了聊天室");
                        }
                    } else {
                        appendToChatArea("其他用户", message);
                    }
                }
            } catch (IOException e) {
                if (!socket.isClosed()) {
                    appendToChatArea("系统", "从服务器接收消息时出错: " + e.getMessage());
                    e.printStackTrace();
                }
            } finally {
                close();
            }
        }
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SwingChatClient client = new SwingChatClient();
                client.setVisible(true);
            }
        });
    }
} 